import { resolve } from 'node:path'
import UnoCSS from 'unocss/vite'
import { defineConfig, loadEnv } from 'vite'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import { createVitePlugins } from './build/plugin'
import { createProxy } from './build/proxy'
import { wrapperEnv } from './build/utils'
import { engines, name, version } from './package.json'

function pathResolve(dir) {
  return resolve(process.cwd(), '.', dir)
}

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const isBuild = command === 'build'
  const env = loadEnv(mode, process.cwd(), '')

  // 转换loadEnv中的参数类型
  const viteEnv = wrapperEnv(env)
  const { VITE_PUBLIC_PATH, VITE_PORT, VITE_PROXY, VITE_DROP_CONSOLE } = viteEnv

  return {
    base: VITE_PUBLIC_PATH,
    resolve: {
      alias: [
        {
          find: /@wails\//,
          replacement: `${pathResolve('bindings/SoulLantern/backend')}/`,
        },
        {
          find: /@\//,
          replacement: `${pathResolve('src')}/`,
        },
      ],
    },

    css: {
      devSourcemap: !isBuild,
    },

    // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
    server: {
      port: VITE_PORT,
      host: true,
      open: false,
      // Load proxy configuration from .env
      proxy: createProxy(VITE_PROXY),
      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ['./index.html', './src/{views,components}/*.1'],
      },
    },

    plugins: [...createVitePlugins(viteEnv), UnoCSS(), vueSetupExtend()],

    define: {
      // 获取项目信息， window.__APP_INFO__
      __APP_INFO__: JSON.stringify({
        name,
        version,
        engines,
        lastBuildTime: new Date().toLocaleString(),
      }),
    },

    build: {
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 3000,
      rollupOptions: {
        // 静态资源分类打包
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        },
      },
    },

    esbuild: {
      pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
    },
  }
})
